package cn.xl.xxl.tools;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.location.LocationManager;
import android.net.Uri;
import android.telephony.TelephonyManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StrikethroughSpan;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

//import android.util.Log;

@SuppressLint("DefaultLocale")
public class Tools {

	/**
	 * ͨ工具类
	 * 
	 * @param url
	 * @return
	 */
	public static String getFileNameFromUrl(String url) {
		String[] _strTemp = url.split("/");
		int _count = _strTemp.length;
		return _strTemp[_count - 1];
	}

	/**
	 * 首次打开APP判断
	 * */
	public void setNewVersion(boolean isNew) {
		Editor edit = preferences.edit();
		edit.putBoolean("isFirstApp", isNew);
		edit.commit();
	}

	public boolean getNewVersion() {
		return preferences.getBoolean("isFirstApp", true);
	}

	/**
	 * 参数版本判断
	 * */
	public void setParamVer(int paramVer) {
		Editor edit = preferences.edit();
		edit.putInt("paramVer", paramVer);
		edit.commit();
	}

	public int getParamVer() {
		return preferences.getInt("paramVer", -1);
	}

	private static ArrayList<Activity> activities;
	private static SharedPreferences preferences;

	static Tools gTools = null;
	static Calendar calendar = Calendar.getInstance();
	private static Context context;

	public static Tools getInstance() {
		if (gTools == null) {
			gTools = new Tools();
			activities = new ArrayList<Activity>();
		}
		return gTools;
	}

	public static Tools getInstance(Context context) {
		Tools.context = context;
		if (gTools == null) {
			gTools = new Tools();
			activities = new ArrayList<Activity>();
		}
		preferences = context.getSharedPreferences("UserInfo",
				Context.MODE_PRIVATE);
		return gTools;

	}

	public SharedPreferences getPreferences() {
		return preferences;
	}

	private static ArrayList<Activity> payAct = new ArrayList<Activity>();// 保存的act

	public static void clearAct() {
		payAct.clear();
	}

	public static void addAct(Activity act) {
		payAct.add(act);
	}

	public static void fishPayAct() {
		for (Activity a : payAct) {
			a.finish();
		}
		payAct.clear();
	}

	private String userName = "";
	private String token = "";
	private String member_id = "";

//	public void setUserName(String userName) {
//		this.userName = userName;
//	}

//	public String getUserName() {
//		if (isEmpty(userName)) {
//			ACache aCache = ACache.get();
//			UserInfo userInfo = (UserInfo) aCache.getAsObject("USERINFO");
//			if (userInfo != null) {
//				userName = userInfo.getUsername();
//				return userName;
//			} else {
//				return userName;
//			}
//		}
//		return userName;
//	}

//	public String getToken() {
//		if (isEmpty(token)) {
//			ACache aCache = ACache.get();
//			UserInfo userInfo = (UserInfo) aCache.getAsObject("USERINFO");
//			if (userInfo != null) {
//				token = userInfo.getToken();
//				return userInfo.getToken();
//			} else {
//				return token;
//			}
//		}
//		return token;
//	}

//	public String getMember_id() {
//		if (isEmpty(member_id)) {
//			ACache aCache = ACache.get();
//			UserInfo userInfo = (UserInfo) aCache.getAsObject("USERINFO");
//			if (userInfo != null) {
//				member_id = userInfo.getMemberId();
//				return member_id;
//			} else {
//				return member_id;
//			}
//		}
//		return member_id;
//	}

//	public void setMember_id(String member_id) {
//		this.member_id = member_id;
//	}
//
//	public void setToken(String token) {
//		this.token = token;
//	}
//
//	public void quitUserInfo() {
//		ACache aCache = ACache.get();
//		UserInfo userInfo = (UserInfo) aCache.getAsObject("USERINFO");
//		userInfo.setToken("");
//		aCache.put("USERINFO", userInfo);
//		token = "";
//	}

	private String url;

//	public String getURL() {
//		if (isEmpty(url)) {
//			ACache aCache = ACache.get();
//			url = aCache.getAsString("DOWNURL");
//			return url;
//		}
//		return url;
//	}

//	public void setURL(String URL) {
//		this.url = URL;
//		ACache aCache = ACache.get();
//		aCache.put("DOWNURL", url);
//	}

	/**
	 * 
	 * 清除数据
	 * 
	 * */
	public void clearUserInfo() {
		Editor edit = preferences.edit();
		edit.clear().commit();
	}

	// 圆角图片
	public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(0, 0, bitmap.getWidth(),
				bitmap.getHeight());
		final float scale = bitmap.getWidth();
		// final float scaleH = bitmap.getHeight();
		final float roundPx = (int) (pixels * scale / 80 + 0.5f);
		// final float roundPxH = (int)(pixels*scaleH/80 +0.5f);
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}

	/**
	 * 圆形图片
	 * 
	 * */
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = bitmap.getWidth() / 2;
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}

	/**
	 * 
	 * 格式化数字为：1.00
	 * 
	 * */
	@SuppressLint("DefaultLocale")
	public static String getAmount1(long lAmt) {
		double d = lAmt;
		d = d / 100.0;
		return String.format("%.2f", d);
	}

	/**
	 * 
	 * 格式化数字为：1.00
	 * 
	 * */
	@SuppressLint("DefaultLocale")
	public static String getAmountD(Double lAmt) {
		double d = lAmt;
		d = d / 100.0;
		return String.format("%.2f", d);
	}

	/**
	 * 
	 * @param text
	 *            : 价格文字数据
	 * @param start
	 *            : 价格在文字串中的起始位置
	 * @param bdel
	 *            : 是否加删除线
	 * @param color
	 *            : 字体颜色
	 * @param fontsize
	 *            : 字体相对默认字体放大倍数
	 * @return
	 */
	public static SpannableString getPriceSpanStr(String text, int start,
			boolean bdel, int color, float fontsize) {
		try {
			SpannableString result = new SpannableString(text);
			int len = text.length();
			result.setSpan(new ForegroundColorSpan(color), start, len - 2,
					Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			if (bdel)
				result.setSpan(new StrikethroughSpan(), start, len - 2,
						Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			result.setSpan(new RelativeSizeSpan(fontsize), start, len - 2,
					Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 原字体的1.5倍

			// 上标
			result.setSpan(new ForegroundColorSpan(color), len - 2, len,
					Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			result.setSpan(new RelativeSizeSpan(fontsize * 0.8f), len - 2, len,
					Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 原字体的1.5倍
			// result.setSpan(new SuperscriptSpan(), len - 2, len,
			// Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 设置上标
			if (bdel)
				result.setSpan(new StrikethroughSpan(), len - 2, len,
						Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			return result;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 
	 * 分享
	 * 
	 * */
	public static void sharApp(Activity activity, String mParamCorpDesc,
			String mParamName, String mParamUseComent) {
		Intent shareInt = new Intent(Intent.ACTION_SEND);
		shareInt.setType("text/plain");
		shareInt.putExtra(Intent.EXTRA_SUBJECT, "选择分享方式");
		String shareText = "【商户】" + mParamCorpDesc + '\n' + "【名称】" + mParamName
				+ '\n' + "【介绍】" + mParamUseComent + '\n'
				+ "【APP下载网址】 http://www.yiruipay.com" + '\n' + "【来源 亿睿科技】";
		shareInt.putExtra(Intent.EXTRA_TEXT, shareText);
		// 分享图片：shareInt.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(gifFile));
		shareInt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		activity.startActivity(shareInt);

	}

	/**
	 * 
	 * MD5算法
	 * 
	 * */
	public static String Md5(String plainText, boolean isLong) {
		StringBuffer buf = null;
		if ("".equals(plainText)) {
			return "";
		}
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();

			int i;

			buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}

			// Log.e("result","result: " + buf.toString());// 32位的加密
			//
			// Log.e("result","result: " + buf.toString().substring(8, 24));//
			// 16位的加密

		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (isLong) {
			return buf.toString();
		}
		return (buf.toString().substring(8, 24)).toUpperCase();
	}

	/**
	 * 有效期
	 * 
	 * **/
	public static String getExplain(String start_date, String expire_date) {

		start_date = getLocalShowDate(start_date) + "-"
				+ getLocalShowDate(expire_date);

		return start_date;

	}

	// 根据yyyymmddhhmmss串获得本地显示的时间串
	public static String getLocalShowDate(String strDate) {
		try {
			String result = strDate.substring(0, 4) + "."
					+ strDate.substring(4, 6) + "." + strDate.substring(6, 8);
			return result;
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 根据YYYYMMDDHHMMSS串获得本地显示的时间串 XXXX年MM月DD日 HH：MM：SS
	 * */
	public static String getHistoryShowDate(String strDate) {
		try {
			String result = "";

			if (strDate.length() == 8)
				result = strDate.substring(0, 4) + "年"
						+ strDate.substring(4, 6) + "月"
						+ strDate.substring(6, 8) + "日";
			else if (strDate.length() == 14)
				result = strDate.substring(0, 4) + "年"
						+ strDate.substring(4, 6) + "月"
						+ strDate.substring(6, 8) + "日  "
						+ strDate.substring(8, 10) + ":"
						+ strDate.substring(10, 12) + ":"
						+ strDate.substring(12);
			return result;
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 根据YYMMDDHHMMSS串获得本地显示的时间串 XXXX年MM月DD日 HH时MM分SS秒
	 * */
	public static String getHSDate(String strDate) {
		try {
			String result = "";

			if (strDate.length() == 6)
				result = strDate.substring(0, 2) + "年"
						+ strDate.substring(4, 6) + "月"
						+ strDate.substring(6, 8) + "日";
			else if (strDate.length() == 12)
				result = strDate.substring(2, 4) + "月"
						+ strDate.substring(4, 6) + "日  "
						+ strDate.substring(6, 8) + "时"
						+ strDate.substring(8, 10) + "分"
						+ strDate.substring(10);
			return result;
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 
	 * 电话显示
	 * 
	 * */
	public static String getTel_no(String tel_no) {
		String s = "***********";
		if (tel_no.length() < 8) {
			tel_no = tel_no.substring(0, 3)
					+ s.substring(0, tel_no.length() - 3);
			return tel_no;
		}
		String tel_midd = tel_no.substring(3, tel_no.length() - 3);
		tel_no = tel_no.replaceAll(tel_midd, s.substring(0, tel_midd.length()));
		return tel_no;

	}

	/**
	 * 
	 * 添加你打开的activity
	 * 
	 * */
	public void addActivity(Activity activity) {
		activities.add(activity);
	}

	/**
	 * 
	 * 关闭所有activity
	 * 
	 * */
	public void romoveAllActivity() {
		for (int i = 0; i < activities.size(); i++) {
			activities.get(i).finish();
		}
	}

	/**
	 * 
	 * 关闭所有activity
	 * 
	 * */
	public void romoveLastActivity() {
		for (int i = 0; i < activities.size() - 1; i++) {
			activities.get(i).finish();
		}
	}

	public String getPublicKey() {
		return preferences.getString("publicKey", null);
	}

	/**
	 * 
	 * 根据yyyymmddhhmmss串获得本地显示的时间串
	 * 
	 * */
	public static String getLocalShowDateAndHM(String strDate) {// 20150212134936
		try {
			String result = "";

			if (strDate.length() == 8)
				result = strDate.substring(0, 4) + "-"
						+ strDate.substring(4, 6) + "-"
						+ strDate.substring(6, 8);
			else if (strDate.length() == 14)
				result = strDate.substring(0, 4) + "-"
						+ strDate.substring(4, 6) + "-"
						+ strDate.substring(6, 8) + " "
						+ strDate.substring(8, 10) + ":"
						+ strDate.substring(10, 12) + ":"
						+ strDate.substring(12);
			return result;
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 
	 * 根据yyyymmddhhmmss串获得本地显示的时间串 return yyyy/mm/dd hh:mm:ss
	 * */
	public static String getShowDateAndHM(long strDate) {// 20150212134936
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		// 前面的lSysTime是秒数，先乘1000得到毫秒数，再转为java.util.Date类型
		Date date = new Date(strDate);
		String sDateTime = sdf.format(date); // 得到精确到秒的表示：08/31/2006 21:08:00
		return sDateTime;
	}

	/**
	 * 
	 * 倒计时 hh:mm:ss
	 * */
	public static String getCountdown(long endtimes) {// 20150212134936
		if (endtimes > 0) {
			StringBuffer sb = new StringBuffer();
			int nd = 24 * 60 * 60 * 100;// 一天的毫秒数
			int nh = 60 * 60 * 100;// 一小时的毫秒数
			int nm = 60 * 100;// 一分钟的毫秒数
			int ns = 1 * 100;// 一秒钟的毫秒数
			long day = endtimes / nd;// 计算差多少天
			long hour = endtimes % nd / nh + day * 24;// 计算差多少小时
			long min = endtimes % nd % nh / nm + day * 24 * 60;// 计算差多少分钟
			long sec = endtimes % nd % nh % nm / ns;// 计算差多少秒
			long millisec = endtimes % nd % nh % nm % ns;// 计算差多少秒
			sb.append("0" + min + ":");
			if (sec > 9) {
				sb.append(sec);
			} else {
				sb.append("0" + sec);
			}
			sb.append(":");
			if (millisec > 9) {
				sb.append(millisec);
			} else {
				sb.append("0" + millisec);
			}
			return sb.toString();
		}
		return "00:00:00";
	}

	/**
	 * 
	 * 倒计时 hh:mm:ss
	 * */
	public static long getCountTime(long endtimes) {
		long cdtime = 30000;
		long millis = System.currentTimeMillis();
		if (endtimes - millis > 0) {
			return (millis - endtimes) / 10;
		}else if((millis - endtimes)<300000){
			return (300000-(millis - endtimes))/10;
		}
		return cdtime;// 20150212134936
	}

	/**
	 * 获取当前时间 根据yyyy-mm-dd HH：mm：ss
	 * */
	public static String getDate() {
		String result = "";
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");// 定义日期格式
		result = format.format(new Date());
		return getLocalShowDateAndHM(result);
	}

	/**
	 * 
	 * 根据yyyymmdd串获得本地显示的时间串 不管几位时间格式只取8位时间
	 * */
	public static String getLocalShow8DateAndHM(String strDate) {// 20150212134936
		try {
			String result = "";

			if (strDate.length() == 8)
				result = strDate.substring(0, 4) + "-"
						+ strDate.substring(4, 6) + "-"
						+ strDate.substring(6, 8);
			else if (strDate.length() == 14)
				result = strDate.substring(0, 4) + "-"
						+ strDate.substring(4, 6) + "-"
						+ strDate.substring(6, 8);
			return result;
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 获得km
	 * */
	public static String getDistance(double distance) {
		double parseDouble = distance / 1000.0;
		String distanceS = String.format("%.2f", parseDouble);
		return distanceS + "公里";
	}

	/**
	 * 拨打电话 跳转到拨号界面
	 * */
	public static void toTel(String tel, Context context) {
		Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel));
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}

	// /**
	// * 拨打电话----需要权限 <uses-permission
	// android:name="android.permission.CALL_PHONE"></uses-permission>
	// * 直接拨打
	// * */
	// public static void dialTel(String tel, Context context){
	// Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + tel));
	// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	// context.startActivity(intent);
	// }

	/**
	 * 手机号码验证
	 * 
	 * */
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0,0-9])|(14[0,0-9])|(177))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	/**
	 * 电话号码验证
	 * 
	 * @param str
	 * @return 验证通过返回true
	 */
	public static boolean isPhone(String str) {
		Pattern p1 = null, p2 = null;
		Matcher m = null;
		boolean b = false;
		p1 = Pattern.compile("^[0][1-9][0-9]{3,10}$"); // 验证带区号的
		p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$"); // 验证没有区号的
		if (str.length() > 9) {
			m = p1.matcher(str);
			b = m.matches();
		} else {
			m = p2.matcher(str);
			b = m.matches();
		}
		return b;
	}

	/**
	 * 
	 * 翼支付验证
	 * */
	public static boolean isYiPay(String mobiles) {
		Pattern p = Pattern.compile("^((153)|(133)|(18[0,9,1])|(177))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();

	}

	/**
	 * email验证
	 * 
	 * */
	public static boolean isEmail(String email) {
		String str = "^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);
		return m.matches();
	}

	/**
	 * 密码验证
	 * 
	 * */

	public static boolean isPwd(String pwd) {
		String str = "^[0-9a-zA-Z]{6,16}$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(pwd);
		return m.matches();

	}

	/**
	 * 格式化劵码
	 * */
	public static String setCode(String code) {
		if (code == null || code.length() < 12) {
			return code;
		}
		String head = code.substring(0, 4);
		String midd = code.substring(4, 8);
		String last = code.substring(8);
		return head + "-" + midd + "-" + last;

	}

	/**
	 * 1. getPhoneNumber方法返回当前手机的电话号码， 同时必须在androidmanifest.xml中 加入
	 * android.permission.READ_PHONE_STATE 这个权限， 2.
	 * 主流的获取用户手机号码一般采用用户主动发送短信到SP或接收手机来获取。
	 * 
	 * @param context
	 * 
	 */
	public static String getPhoneNumber(Context context) {
		TelephonyManager mTelephonyMgr;
		mTelephonyMgr = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		return mTelephonyMgr.getLine1Number();
	}

	/**
	 * 取EditText值，String
	 * */
	public static String getTextValue(TextView dt) {
		String result = "";
		if (dt != null && dt.getText().toString() != null
				&& !"".equals(dt.getText().toString())) {
			result = dt.getText().toString();
		}
		return result;
	}

	public static boolean isNumber(String str) {
		final String reg = "\\d+\\.{0,1}\\d*";
		return str.matches(reg);
	}

	/**
	 * 去掉-的日期
	 * */
	public static String getDate(TextView dt) {
		String result = "";
		if (dt != null && dt.getText().toString() != null
				&& !"".equals(dt.getText().toString())) {
			result = dt.getText().toString().replaceAll("-", "");
		}
		return result;
	}

	/**
	 * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
	 * 
	 * @param context
	 * @return true 表示开启
	 */
	public static final boolean isOPenGPS(final Context context) {
		LocationManager locationManager = (LocationManager) context
				.getSystemService(Context.LOCATION_SERVICE);
		// 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
		boolean gps = locationManager
				.isProviderEnabled(LocationManager.GPS_PROVIDER);
		// 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
		boolean network = locationManager
				.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
		if (gps || network) {
			return true;
		}

		return false;
	}

	private final static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;

	/**
	 * 火星坐标转百度坐标
	 * 
	 * */
//	public static BDLatLng GCJtoBD(double gg_lat, double gg_lon) {
//		double x = gg_lon, y = gg_lat;
//		double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
//		double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
//		double bd_lon = z * Math.cos(theta) + 0.0065;
//		double bd_lat = z * Math.sin(theta) + 0.006;
//		BDLatLng bdLatLng = new BDLatLng();
//		bdLatLng.setBd_lat(bd_lat);
//		bdLatLng.setBd_lon(bd_lon);
//		return bdLatLng;
//	}

	/**
	 * 百度坐标转火星坐标
	 * 
	 * */
//	public static GCJLatLng BDtoGCJ(double bd_lat, double bd_lon) {
//		double x = bd_lon - 0.0065, y = bd_lat - 0.006;
//		double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
//		double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
//		double gcj_lon = z * Math.cos(theta);
//		double gcj_lat = z * Math.sin(theta);
//		GCJLatLng gcjLatLng = new GCJLatLng();
//		gcjLatLng.setGcj_lat(gcj_lat);
//		gcjLatLng.setGcj_lon(gcj_lon);
//		return gcjLatLng;
//	}

	static double PI = 3.14159265358979324;
	double xpi = 3.14159265358979324 * 3000.0 / 180.0;

	public static boolean outOfChina(double lat, double lon) {
		if (lon < 72.004 || lon > 137.8347)
			return true;
		if (lat < 0.8293 || lat > 55.8271)
			return true;
		return false;
	}

	public static double transformLat(double x, double y) {
		double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y
				+ 0.2 * Math.sqrt(Math.abs(x));
		ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
		ret += (20.0 * Math.sin(y * PI) + 40.0 * Math.sin(y / 3.0 * PI)) * 2.0 / 3.0;
		ret += (160.0 * Math.sin(y / 12.0 * PI) + 320 * Math.sin(y * PI / 30.0)) * 2.0 / 3.0;
		return ret;
	}

	public static double transformLon(double x, double y) {
		double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1
				* Math.sqrt(Math.abs(x));
		ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
		ret += (20.0 * Math.sin(x * PI) + 40.0 * Math.sin(x / 3.0 * PI)) * 2.0 / 3.0;
		ret += (150.0 * Math.sin(x / 12.0 * PI) + 300.0 * Math.sin(x / 30.0
				* PI)) * 2.0 / 3.0;
		return ret;
	}

//	public static Dgcj delta(double lat, double lon) {
//
//		// Krasovsky 1940
//		//
//		// a = 6378245.0, 1/f = 298.3
//		// b = a * (1 - f)
//		// ee = (a^2 - b^2) / a^2;
//		double a = 6378245.0; // a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
//		double ee = 0.00669342162296594323; // ee: 椭球的偏心率。
//		double dLat = transformLat(lon - 105.0, lat - 35.0);
//		double dLon = transformLon(lon - 105.0, lat - 35.0);
//		double radLat = lat / 180.0 * PI;
//		double magic = Math.sin(radLat);
//		magic = 1 - ee * magic * magic;
//		double sqrtMagic = Math.sqrt(magic);
//		dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * PI);
//		dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * PI);
//		Dgcj dgcj = new Dgcj();
//		dgcj.lat = dLat;
//		dgcj.lon = dLon;
//		return dgcj;
//	}

//	public static WgsLatLng gcj_encrypt(double wgsLat, double wgsLon) {
//		WgsLatLng wgsLatLng = new WgsLatLng();
//		if (outOfChina(wgsLat, wgsLon)) {
//			wgsLatLng.lat = wgsLat;
//			wgsLatLng.lon = wgsLon;
//			return wgsLatLng;
//		}
//
//		Dgcj d = delta(wgsLat, wgsLon);
//		wgsLatLng.lat = wgsLat + d.lat;
//		wgsLatLng.lon = wgsLat + d.lon;
//		return wgsLatLng;
//	}

	/**
	 * 
	 * @param 火星TOGPS
	 * @param
	 * @return
	 */
//	public static GPSLatLng GCJtoWGS(double gcjLat, double gcjLon) {
//		double initDelta = 0.01;
//		double threshold = 0.000000001;
//		double dLat = initDelta, dLon = initDelta;
//		double mLat = gcjLat - dLat, mLon = gcjLon - dLon;
//		double pLat = gcjLat + dLat, pLon = gcjLon + dLon;
//		double wgsLat, wgsLon, i = 0;
//		while (true) {
//			wgsLat = (mLat + pLat) / 2;
//			wgsLon = (mLon + pLon) / 2;
//			WgsLatLng tmp = gcj_encrypt(wgsLat, wgsLon);
//			dLat = tmp.lat - gcjLat;
//			dLon = tmp.lon - gcjLon;
//			if ((Math.abs(dLat) < threshold) && (Math.abs(dLon) < threshold))
//				break;
//			if (dLat > 0)
//				pLat = wgsLat;
//			else
//				mLat = wgsLat;
//			if (dLon > 0)
//				pLon = wgsLon;
//			else
//				mLon = wgsLon;
//
//			if (++i > 10000)
//				break;
//		}
//		// console.log(i);
//		GPSLatLng gpsLatLng = new GPSLatLng();
//		gpsLatLng.lat = wgsLat;
//		gpsLatLng.lon = wgsLon;
//		return gpsLatLng;
//	}

	public static String getFormatPhone(String phone) {
		if (phone.length() < 11) {
			return phone;
		} else {
			String head = phone.substring(0, 4);
			String midd = phone.substring(4, 8);
			String last = phone.substring(8);
			phone = head + " " + midd + " " + last;
		}
		return phone;
	}

	/**
	 * 日期转化
	 * 
	 * @return
	 */
	public static String StringData() {
		final Calendar c = Calendar.getInstance();
		c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
		// String mYear = String.valueOf(c.get(Calendar.YEAR)); // 获取当前年份
		String mMonth = String.valueOf(c.get(Calendar.MONTH) + 1);// 获取当前月份
		String mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));// 获取当前月份的日期号码
		String mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
		if ("1".equals(mWay)) {
			mWay = "天";
		} else if ("2".equals(mWay)) {
			mWay = "一";
		} else if ("3".equals(mWay)) {
			mWay = "二";
		} else if ("4".equals(mWay)) {
			mWay = "三";
		} else if ("5".equals(mWay)) {
			mWay = "四";
		} else if ("6".equals(mWay)) {
			mWay = "五";
		} else if ("7".equals(mWay)) {
			mWay = "六";
		}
		return mMonth + "月" + mDay + "日" + "  星期" + mWay;
	}

	/**
	 * 获取单天推送日期 时间 格式：8月7日 星期五 15:55
	 * 
	 * @return
	 */
	public static String getOrderTime(String strDate) {
		String result = "";
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");// 定义日期格式
		Date date = null;
		try {
			date = format.parse(strDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
		String mMonth = String.valueOf(cal.get(Calendar.MONTH) + 1);// 获取当前月份
		String mDay = String.valueOf(cal.get(Calendar.DAY_OF_MONTH));// 获取当前月份的日期号码
		String mWay = String.valueOf(cal.get(Calendar.DAY_OF_WEEK));
		if (strDate.length() == 14) {
			result = strDate.substring(8, 10) + ":" + strDate.substring(10, 12);
			// + ":" + strDate.substring(12);
		}
		if ("1".equals(mWay)) {
			mWay = "天";
		} else if ("2".equals(mWay)) {
			mWay = "一";
		} else if ("3".equals(mWay)) {
			mWay = "二";
		} else if ("4".equals(mWay)) {
			mWay = "三";
		} else if ("5".equals(mWay)) {
			mWay = "四";
		} else if ("6".equals(mWay)) {
			mWay = "五";
		} else if ("7".equals(mWay)) {
			mWay = "六";
		}
		return mMonth + "月" + mDay + "日" + "  星期" + mWay + "  " + result;
	}

	/**
	 * 获取头像名称
	 */
//	public static String getPhotoName() {
//		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_hhmmss");
//		String photoName = getInstance().getUserName() + "_"
//				+ format.format(new Date());
//		return photoName;
//	}

	/**
	 * 用来判断服务是否运行.
	 * 
	 * @param context
	 * @param className
	 *            判断的服务名字
	 * @return true 在运行 false 不在运行
	 */
	public static boolean isServiceRunning(Context mContext, String className) {
		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager
				.getRunningServices(Integer.MAX_VALUE);
		if (!(serviceList.size() > 0)) {
			return false;
		}
		for (ActivityManager.RunningServiceInfo r : serviceList) {
			if (r.service.getClassName().equals(className) == true) {
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}

	/**
	 * 检查手机上是否安装了指定的软件
	 * 
	 * @param context
	 * @param packageName
	 *            ：应用包名
	 * @return
	 */
	// public static ArrayList<MapAPP> scanMapApp(Context context) {
	// // 获取packagemanager
	// final PackageManager packageManager = context.getPackageManager();
	// // 获取所有已安装程序的包信息
	// List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
	// // 用于存储所有已安装程序的包名
	// ArrayList<MapAPP> mapApps = new ArrayList<MapAPP>();
	// // 从pinfo中将包名字逐一取出，压入pName list中
	// if (packageInfos != null) {
	// for (int i = 0; i < packageInfos.size(); i++) {
	// String packName = packageInfos.get(i).packageName; // 包名
	// String appName = packageInfos.get(i).applicationInfo.loadLabel(
	// context.getPackageManager()).toString();// app名
	// if ("com.baidu.BaiduMap".equals(packName)) {
	// MapAPP app = new MapAPP();
	// app.setMap_appName(appName);
	// app.setMap_packageName(packName);
	// mapApps.add(app);
	// } else if ("com.autonavi.minimap".equals(packName)) {
	// MapAPP app = new MapAPP();
	// app.setMap_appName(appName);
	// app.setMap_packageName(packName);
	// mapApps.add(app);
	// }
	//
	// }
	// }
	// // 判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
	// // packageNames.contains(packageName)
	// return mapApps;
	// }

	public static byte[] str2Bcd(String asc) {
		int len = asc.length();
		int mod = len % 2;
		if (mod != 0) {
			asc = "0" + asc;
			len = asc.length();
		}
		byte abt[] = new byte[len];
		if (len >= 2) {
			len = len / 2;
		}
		byte bbt[] = new byte[len];
		abt = asc.getBytes();
		int j, k;
		for (int p = 0; p < asc.length() / 2; p++) {
			if ((abt[2 * p] >= '0') && (abt[2 * p] <= '9')) {
				j = abt[2 * p] - '0';
			} else if ((abt[2 * p] >= 'a') && (abt[2 * p] <= 'z')) {
				j = abt[2 * p] - 'a' + 0x0a;
			} else {
				j = abt[2 * p] - 'A' + 0x0a;
			}
			if ((abt[2 * p + 1] >= '0') && (abt[2 * p + 1] <= '9')) {
				k = abt[2 * p + 1] - '0';
			} else if ((abt[2 * p + 1] >= 'a') && (abt[2 * p + 1] <= 'z')) {
				k = abt[2 * p + 1] - 'a' + 0x0a;
			} else {
				k = abt[2 * p + 1] - 'A' + 0x0a;
			}
			int a = (j << 4) + k;
			byte b = (byte) a;
			bbt[p] = b;
		}
		return bbt;
	}

	/**
	 * @功能: BCD码转为10进制串(阿拉伯数据)
	 * @参数: BCD码
	 * @结果: 10进制串
	 */
	public static String bcd2Str(byte[] bytes) {
		StringBuffer temp = new StringBuffer(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			temp.append((byte) ((bytes[i] & 0xf0) >>> 4));
			temp.append((byte) (bytes[i] & 0x0f));
		}
		return temp.toString().substring(0, 1).equalsIgnoreCase("0") ? temp
				.toString().substring(1) : temp.toString();
	}

	public static byte Check(byte[] s) {
		byte mm;
		mm = (byte) (s[0] ^ s[1]);
		if (s.length > 2) {
			for (int i = 2; i < s.length; i++) {
				mm = (byte) (mm ^ s[i]);
			}
		}
		return mm;
	}

	/**
	 * 
	 * @param body
	 * @param
	 * @return 获得报文
	 */
	private static byte[] Packets(byte[] body, byte check) {
		byte m1 = (byte) 0x7e;
		byte m2 = (byte) 0x7e;
		int len = body.length + 3;
		byte[] retBuf = new byte[len];
		int index = 0;
		retBuf[index++] = m1;
		for (int i = 0; i < body.length; i++) {
			retBuf[index++] = body[i];
		}
		retBuf[index++] = check;
		retBuf[index++] = m2;
		return retBuf;
	}

	/**
	 * 
	 * @param body
	 * @param
	 * @return 获得报文
	 */
	private static byte[] Packets(byte[] body, byte[] check) {
		byte m1 = (byte) 0x7e;
		byte m2 = (byte) 0x7e;
		int len = body.length + 2 + check.length;
		byte[] retBuf = new byte[len];
		int index = 0;
		retBuf[index++] = m1;
		for (int i = 0; i < body.length; i++) {
			retBuf[index++] = body[i];
		}
		for (int i = 0; i < check.length; i++) {
			retBuf[index++] = check[i];
		}
		retBuf[index++] = m2;
		return retBuf;
	}

	/**
	 * 转义
	 */

	public static byte[] Escape(byte[] body, byte cheak) {
		Byte K1 = (byte) 0x7e;
		Byte K2 = (byte) 0x7d;
		byte m1 = (byte) 0x02;// 0x7e <————> 0x7d 后紧跟一个 0x02 。
		byte m2 = (byte) 0x01;// 0x7d <————> 0x7d 后紧跟一个 0x01
		ArrayList<Integer> integers = new ArrayList<Integer>();
		for (int i = 0; i < body.length; i++) {
			Byte b = body[i];
			if (b.equals(K1) || b.equals(K2)) {
				integers.add(i);
			}
		}
		byte[] newBody = null;
		if (integers.size() > 0) {
			Integer newIndex = 0;
			newBody = new byte[body.length + integers.size()];
			for (int i = 0; i < integers.size(); i++) {
				for (int j = newIndex; j <= integers.get(i); j++) {
					newBody[j] = body[j];
					if (integers.get(i) == j) {
						Byte b = newBody[j];
						if (b.equals(K1)) {
							newBody[j] = K2;
							newBody[j + 1] = m1;
						} else if (b.equals(K2)) {
							newBody[j] = K2;
							newBody[j + 1] = m2;
						}
					}
				}
				newIndex = integers.get(i) + 2;
				if (i == integers.size() - 1) {
					for (int j = integers.get(integers.size() - 1) + 1; j < body.length; j++) {
						newBody[j + 1] = body[j];
					}
				}
			}
		}

		Byte c = cheak;
		byte[] cs = null;
		if (c.equals(K1) || c.equals(K2)) {
			cs = new byte[2];
			if (c.equals(K1)) {
				cs[0] = K2;
				cs[1] = m1;
			} else if (c.equals(K2)) {
				cs[0] = K2;
				cs[1] = m2;
			}
		}

		if (newBody != null) {
			if (cs != null) {
				return Packets(newBody, cs);
			} else {
				return Packets(newBody, cheak);
			}
		} else {
			if (cs != null) {
				return Packets(body, cs);
			} else {
				return Packets(body, cheak);
			}
		}
	}

	/**
	 * 
	 * @param bSLength
	 * @return 长度
	 */
	public static byte[] lengthToByte(String bSLength) {
		if (bSLength.length() < 16) {
			String heads = "0000000000000000";// 消息体属性，现阶段无加密情况
			bSLength = heads.substring(0, heads.length() - bSLength.length())
					+ bSLength;
		}
		String binaryString2hexString = binaryString2hexString(bSLength);
		return str2Bcd(binaryString2hexString);
	}

	/**
	 * 
	 * @param bSLength
	 * @return 业务长度 4位
	 */
	public static byte[] rlengthToByte(String bSLength) {
		if (bSLength.length() < 32) {
			String heads = "00000000000000000000000000000000";// 消息体属性，现阶段无加密情况
			bSLength = heads.substring(0, heads.length() - bSLength.length())
					+ bSLength;
		}
		String binaryString2hexString = binaryString2hexString(bSLength);
		return str2Bcd(binaryString2hexString);
	}

	public static byte[] combineByte(byte[] buf1, byte[] buf2) {
		int len = buf1.length + buf2.length;
		byte[] retBuf = new byte[len];
		int index = 0;

		for (int i = 0; i < buf1.length; i++) {
			retBuf[index++] = buf1[i];
		}

		for (int i = 0; i < buf2.length; i++) {
			retBuf[index++] = buf2[i];
		}

		return retBuf;
	}

	public static byte[] combineByte(byte[] buf1, byte[] buf2, byte[] buf3,
			byte[] buf4) {
		int len = buf1.length + buf2.length + buf3.length + buf4.length;
		byte[] retBuf = new byte[len];
		int index = 0;

		for (int i = 0; i < buf1.length; i++) {
			retBuf[index++] = buf1[i];
		}

		for (int i = 0; i < buf2.length; i++) {
			retBuf[index++] = buf2[i];
		}
		for (int i = 0; i < buf3.length; i++) {
			retBuf[index++] = buf3[i];
		}
		for (int i = 0; i < buf4.length; i++) {
			retBuf[index++] = buf4[i];
		}

		return retBuf;
	}

	public static byte[] combineByte(byte buf1, byte[] buf2, byte[] buf3,
			byte[] buf4) {
		int len = 1 + buf2.length + buf3.length + buf4.length;
		byte[] retBuf = new byte[len];
		int index = 0;

		for (int i = 0; i < 1; i++) {
			retBuf[index++] = buf1;
		}

		for (int i = 0; i < buf2.length; i++) {
			retBuf[index++] = buf2[i];
		}
		for (int i = 0; i < buf3.length; i++) {
			retBuf[index++] = buf3[i];
		}
		for (int i = 0; i < buf4.length; i++) {
			retBuf[index++] = buf4[i];
		}

		return retBuf;
	}

	/**
	 * 
	 * @param bString
	 * @return 二进制转16进制
	 */
	public static String binaryString2hexString(String bString) {
		if (bString == null || bString.equals("") || bString.length() % 8 != 0)
			return null;
		StringBuffer tmp = new StringBuffer();
		int iTmp = 0;
		for (int i = 0; i < bString.length(); i += 4) {
			iTmp = 0;
			for (int j = 0; j < 4; j++) {
				iTmp += Integer.parseInt(bString.substring(i + j, i + j + 1)) << (4 - j - 1);
			}
			tmp.append(Integer.toHexString(iTmp));
		}
		return tmp.toString();
	}

	/**
	 * 
	 * @param id
	 * @param length
	 *            消息体长度
	 * @param num
	 *            电话
	 * @param SerialNum
	 *            流水号
	 * @return
	 */
	public static byte[] messageBodyHead(String id, int length, String num,
			int SerialNum) {
		byte[] idBcd = str2Bcd(id);
		BigInteger integer = new BigInteger(String.valueOf(length));
		byte[] lengthToByte = Tools.lengthToByte(integer.toString(2));
		BigInteger integer2 = new BigInteger(String.valueOf(SerialNum));
		byte[] SerialNumToByte = Tools.lengthToByte(integer2.toString(2));
		if (num.length() < 12) {
			num = "0" + num;
		}
		byte[] numBcd = str2Bcd(num);
		byte[] combineByte1 = combineByte(idBcd, lengthToByte);
		byte[] combineByte2 = combineByte(numBcd, SerialNumToByte);
		return combineByte(combineByte1, combineByte2);
	}

	/**
	 * 
	 * @param phone
	 * @return 心跳报文
	 */
	public static byte[] getHeartbeat(String id, String messageid) {
		byte[] bodyHead = Tools.messageBodyHead(messageid, 0, id,
				getSerialNumber());
		Log.e("流水", getSerialNumber() + "");
		byte check = Tools.Check(bodyHead);
		setSerialNumber(getSerialNumber() + 1);// 流水递增
		return Tools.Escape(bodyHead, check);

	}

	/**
	 * 
	 * @return tcp 终端注销 就是收车
	 */
//	public static byte[] getLogout(String id, String messageid) {
//		byte[] bodyHead = Tools.messageBodyHead(messageid, 6, id,
//				getSerialNumber());
//		byte[] bcd = str2Bcd(Tools.getInstance().getUserName());
//		byte[] combineByte = combineByte(bodyHead, bcd);
//		byte check = Tools.Check(combineByte);
//		setSerialNumber(getSerialNumber() + 1);// 流水递增
//		return Tools.Escape(combineByte, check);
//
//	}

	/**
	 * 
	 * @param 0900 __028C-驾驶员APP电召抢答应答
	 * @return 位置报文
	 */
//	public static byte[] getOrderReply(byte[] orderNo, String status,
//			SItude itude) {
//		byte f1 = (byte) 0xf1;
//		byte[] idBcd = str2Bcd("028c");
//		byte[] mark = str2Bcd("00000000");
//		byte[] carStatus = str2Bcd(status);
//		int lat = (int) (itude.getLatitude() * 1000000);
//		int lgt = (int) (itude.getLongitude() * 1000000);
//		byte[] latbcd = Tools.str2Bcd(Integer.toHexString(lat));
//		byte[] lgtbcd = Tools.str2Bcd(Integer.toHexString(lgt));
//
//		byte[] high = Tools
//				.get4HSD(Integer.toHexString((int) itude.getHight()));
//		byte[] speed = Tools
//				.get4HSD(Integer.toHexString((int) itude.getSeep()));
//		byte[] direction = Tools.get4HSD(Integer.toHexString((int) itude
//				.getDirection()));
//
//		// byte[] high = Tools.str2Bcd("000");
//		// byte[] speed = Tools.str2Bcd("000");
//		// byte[] direction = Tools.str2Bcd("000");
//
//		SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss");
//		byte[] time = Tools.str2Bcd(format.format(new Date()));
//		byte[] byte1 = combineByte(mark, carStatus, latbcd, lgtbcd);
//		byte[] byte2 = combineByte(high, speed, direction, time);
//		byte[] byte3 = combineByte(byte1, byte2);
//		byte[] rbody = combineByte(orderNo, byte3);
//		BigInteger integer = new BigInteger(String.valueOf(rbody.length));
//		byte[] rlen = Tools.rlengthToByte(integer.toString(2));
//		byte[] body = combineByte(f1, idBcd, rlen, rbody);
//		byte[] bodyHead = Tools.messageBodyHead("0900", body.length, Tools
//				.getInstance().getUserName(), getSerialNumber());
//		byte[] combineByte = combineByte(bodyHead, body);
//		byte check = Tools.Check(combineByte);
//		setSerialNumber(getSerialNumber() + 1);// 流水递增
//		return Tools.Escape(combineByte, check);
//
//	}

	public static byte[] get4HSD(String s) {
		String h = "0000";
		if (s.length() < 4) {
			s = h.substring(0, 4 - s.length()) + s;
		} else if (s.length() > 4) {
			s = h;
		}
		return hexString2Bytes(s);
	}

	/**
	 * 5.3.2.2 0x028D-(驾驶员APP专用)抢答确认应答
	 * 
	 */
//	public static byte[] getConfirm(byte type, byte[] orderNo) {
//		byte[] rbody = new byte[orderNo.length + 1];
//		for (int i = 0; i < orderNo.length; i++) {
//			rbody[i] = orderNo[i];
//		}
//		rbody[rbody.length - 1] = type;
//		byte f1 = (byte) 0xf1;
//		byte[] idBcd = str2Bcd("028d");
//		BigInteger integer = new BigInteger(String.valueOf(rbody.length));
//		byte[] rlen = Tools.rlengthToByte(integer.toString(2));
//		byte[] body = combineByte(f1, idBcd, rlen, rbody);
//		byte[] bodyHead = Tools.messageBodyHead("0900", body.length, Tools
//				.getInstance().getUserName(), getSerialNumber());
//		byte[] combineByte = combineByte(bodyHead, body);
//		byte check = Tools.Check(combineByte);
//		setSerialNumber(getSerialNumber() + 1);// 流水递增
//		return Tools.Escape(combineByte, check);
//	}

	/**
	 * 5.3.2.3 0x028A-(驾驶员APP专用)取消电召结果
	 * 
	 */
//	public static byte[] getConfirmCancel(byte type, byte[] orderNo) {
//		byte[] rbody = new byte[orderNo.length + 1];
//		for (int i = 0; i < orderNo.length; i++) {
//			rbody[i] = orderNo[i];
//		}
//		rbody[rbody.length - 1] = type;
//		byte f1 = (byte) 0xf1;
//		byte[] idBcd = str2Bcd("028a");
//		BigInteger integer = new BigInteger(String.valueOf(rbody.length));
//		byte[] rlen = Tools.rlengthToByte(integer.toString(2));
//		byte[] body = combineByte(f1, idBcd, rlen, rbody);
//		byte[] bodyHead = Tools.messageBodyHead("0900", body.length, Tools
//				.getInstance().getUserName(), getSerialNumber());
//		byte[] combineByte = combineByte(bodyHead, body);
//		byte check = Tools.Check(combineByte);
//		setSerialNumber(getSerialNumber() + 1);// 流水递增
//		return Tools.Escape(combineByte, check);
//	}

	/**
	 * 0x0001-通用应答
	 * 
	 */
//	public static byte[] getCommon(byte[] id, byte[] serNum, String result) {
//		byte[] res = str2Bcd(result);
//		byte[] body = combineByte(id, serNum);
//		body = combineByte(body, res);
//		byte[] bodyHead = Tools.messageBodyHead("0001", body.length, Tools
//				.getInstance().getUserName(), getSerialNumber());
//		byte[] combineByte = combineByte(bodyHead, body);
//		byte check = Tools.Check(combineByte);
//		setSerialNumber(getSerialNumber() + 1);// 流水递增
//		return Tools.Escape(combineByte, check);
//	}

	public static void setSerialNumber(int i) {
		Editor edit = preferences.edit();
		edit.putInt("SerialNumber", i);
		edit.commit();
	}

	public static int getSerialNumber() {
		return preferences.getInt("SerialNumber", 0);
	}

	/**
	 * 
	 * @param 终端id
	 *            ---手机号码 --id 密码 pwd 车牌号：car 手机号码：phone 消息 ID: messageid
	 * @return
	 */

	public static byte[] getALLPackets(String id, String pwd, String carNo,
			String phone, String messageid) {
		if (id.length() < 12) {
			id = "0" + id;
		}
		byte[] idBcd = Tools.str2Bcd(id);// 终端id
		byte[] srtbyte = null;
		try {
			srtbyte = pwd.getBytes("GBK");// 密码
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		byte[] srtbyteCar = null;
		try {
			srtbyteCar = carNo.getBytes("GBK");// 车辆标示
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		byte[] str2Bcd5 = Tools.str2Bcd(Integer.toHexString(pwd.length()));// 密码长度
		byte[] bodyHead = Tools.messageBodyHead(messageid, idBcd.length
				+ srtbyte.length + srtbyteCar.length + str2Bcd5.length, phone,
				getSerialNumber());
		byte[] body = Tools.combineByte(idBcd, str2Bcd5, srtbyte, srtbyteCar);
		byte[] byte1 = Tools.combineByte(bodyHead, body);
		byte check = Tools.Check(byte1);
		final byte[] packets = Tools.Escape(byte1, check);
		setSerialNumber(getSerialNumber() + 1);// 流水递增
		return packets;
	}

	public static byte[] Unpacked(byte[] b) {// 去掉 头尾标识，转义后结果
		byte[] a = new byte[b.length - 2];
		for (int i = 1; i < b.length - 1; i++) {
			a[i - 1] = b[i];
			System.err.format("%02X\n", a[i - 1]);
		}
		Log.e("a....", a.length + "");
		Byte K2 = (byte) 0x7e;
		Byte K1 = (byte) 0x7d;
		Byte m1 = (byte) 0x02;// 0x7e <————> 0x7d 后紧跟一个 0x02 。
		Byte m2 = (byte) 0x01;// 0x7d <————> 0x7d 后紧跟一个 0x01
		ArrayList<Integer> integers = new ArrayList<Integer>();
		for (int i = 0; i < a.length; i++) {
			if (K1.equals((a[i]))) {
				integers.add(i);
				Log.e("a", i + "");
			}
		}
		if (integers.size() > 0) {
			Integer newIndex = 0;
			byte[] c = new byte[a.length - integers.size()];
			Log.e("c....", c.length + "");
			for (int i = 0; i < integers.size(); i++) {
				Integer f = integers.get(i);
				for (int j = newIndex; j <= f; j++) {
					Log.i("j-i:" + (j - i), "j:" + j);
					c[j - i] = a[j];
					if (j == f) {
						if (m1.equals(a[j + 1])) {
							c[j - i] = K2;
						} else if (m2.equals(a[j + 1])) {
							c[j - i] = K1;
						}
					}
				}
				newIndex = integers.get(i) + 2;
				if (i == integers.size() - 1
						&& (c.length > (integers.get(integers.size() - 1) + 2))) {
					for (int j = integers.get(i); j < a.length; j++) {
						if (((j - i) + 1) >= c.length) {
							break;
						}
						Log.i("(j-i)1:" + ((j - i) + 1), "(j)1:" + (j + 2));
						c[(j - i) + 1] = a[j + 2];
					}
				}
			}
			return c;
		} else {
			return a;
		}
	}

	private static String isLongMessage(byte[] bs) {
		String ZERO = "00000000";
		String s = "";
		String s1 = "";
		for (int i = 0; i < bs.length; i++) {
			s = Integer.toBinaryString(bs[i]);
			if (s.length() > 8) {
				s = s.substring(s.length() - 8);
			} else if (s.length() < 8) {
				s = ZERO.substring(s.length()) + s;
			}
			s1 = s1 + s;
		}
		return s1;
	}

	public static byte[] getServiceBody(byte[] b) {
		byte[] len = new byte[2];
		for (int i = 0; i < len.length; i++) {
			len[i] = b[i + 2];
		}
		String longMessage = isLongMessage(len);
		Log.e("longMessage", longMessage);
		if ("1".equals(longMessage.subSequence(2, 3))) {
			int i = Integer.parseInt(
					longMessage.substring(6, longMessage.length()), 2);
			Log.e("Li.....................................", i + "");
			byte[] body = new byte[i];
			for (int j = 0; j < body.length; j++) {
				body[j] = b[16 + j];
			}
			return body;
		}
		String hexString1 = toHexString1(len);
		int i = Integer.parseInt(hexString1, 16);
		Log.e("i.....................................", i + "");
		byte[] body = new byte[i];
		try {
			for (int j = 0; j < body.length; j++) {
				body[j] = b[12 + j];
			}
			return body;
		} catch (Exception e) {
			return null;
		}
	}

	public static String getServiceId(byte[] b) {
		byte[] s = new byte[2];
		for (int i = 0; i < s.length; i++) {
			s[i] = b[i];
		}
		return toHexString1(s);
	}

	/**
	 * 
	 * 获取流水号
	 * */
	public static byte[] getServiceNum(byte[] b) {
		byte[] s = new byte[2];
		for (int i = 0; i < s.length; i++) {
			s[i] = b[i + 11];
		}
		return s;
	}

	/**
	 * 数组转成十六进制字符串
	 * 
	 * @param byte[]
	 * @return HexString
	 */
	public static String toHexString1(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
		}
		return hs;
	}

	public static String toHexString1(byte b) {
		String s = Integer.toHexString(b & 0xFF);
		if (s.length() == 1) {
			return "0" + s;
		} else {
			return s;
		}
	}

	public static boolean isEmpty(String str) {
		if (str == null || str.length() == 0 || "null".equalsIgnoreCase(str)
				|| "".equals(str)) {
			return true;
		}
		return false;
	}

	public void setCarStatus(String status) {
		if (status.length() < 8) {
			status = "0" + status;
			setCarStatus(status);
			return;
		}
		Editor edit = preferences.edit();
		edit.putString("CARSTATUS", status);
		edit.commit();
	}

	public String getCarStatus() {
		return preferences.getString("CARSTATUS", "00000001");
	}

	public String getCar1Status() {
		return preferences.getString("CARSTATUS", "00000006").substring(7, 8);
	}

	public static byte[] getNowDate() {
		SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");// 设置日期格式
		String nowDate = df.format(new Date());
		return str2Bcd(nowDate);
	}

	public static void setCarNo(String carNo) {
		Editor edit = preferences.edit();
		edit.putString("CARNO", carNo);
		edit.commit();
	}

	public static String getCarNo() {
		return preferences.getString("CARNO", "");
	}

	/**
	 * 计算地球上任意两点(经纬度)距离
	 * 
	 * @param long1
	 *            第一点经度
	 * @param lat1
	 *            第一点纬度
	 * @param long2
	 *            第二点经度
	 * @param lat2
	 *            第二点纬度
	 * @return 返回距离 单位：米
	 */
	public static double Distance(double long1, double lat1, double long2,
			double lat2) {
		double a, b, R;
		R = 6378137; // 地球半径
		lat1 = lat1 * Math.PI / 180.0;
		lat2 = lat2 * Math.PI / 180.0;
		a = lat1 - lat2;
		b = (long1 - long2) * Math.PI / 180.0;
		double d;
		double sa2, sb2;
		sa2 = Math.sin(a / 2.0);
		sb2 = Math.sin(b / 2.0);
		d = 2
				* R
				* Math.asin(Math.sqrt(sa2 * sa2 + Math.cos(lat1)
						* Math.cos(lat2) * sb2 * sb2));
		return d;
	}

	/**
	 * 将byte[]转为各种进制的字符串
	 * 
	 * @param bytes
	 *            byte[]
	 * @param radix
	 *            基数可以转换进制的范围，从Character.MIN_RADIX到Character.MAX_RADIX，
	 *            超出范围后变为10进制
	 * @return 转换后的字符串
	 */
	public static String binary(byte[] bytes, int radix) {
		return new BigInteger(1, bytes).toString(radix);// 这里的1代表正数
	}

	/**
	 * 获得公里
	 * */
	public static String getKm(int distance) {
		double parseDouble = Double.parseDouble(String.valueOf(distance));
		parseDouble = parseDouble / 1000;
		String distanceS = String.format("%.1f", parseDouble);
		return distanceS + "公里";
	}

	/**
	 * 格式化时间
	 * 
	 * @param time
	 * @return
	 */
	public static String formatDateTime(String time) {
		String startTime = time;
		Calendar current = Calendar.getInstance();
		if (time.length() < 12) {
			return time;
		}
		if (time.length() <= 14) {
			time = String.valueOf(current.get(Calendar.YEAR)).substring(0, 2)
					+ time;
		}
		time = getLocalShowDateAndHM(time);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (time == null || "".equals(time)) {
			return "";
		}
		Date date = null;
		try {
			date = format.parse(time);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		Calendar today = Calendar.getInstance(); // 今天
		today.set(Calendar.YEAR, current.get(Calendar.YEAR));
		today.set(Calendar.MONTH, current.get(Calendar.MONTH));
		today.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH));
		// Calendar.HOUR——12小时制的小时数 Calendar.HOUR_OF_DAY——24小时制的小时数
		today.set(Calendar.HOUR_OF_DAY, 0);
		today.set(Calendar.MINUTE, 0);
		today.set(Calendar.SECOND, 0);

		Calendar yesterday = Calendar.getInstance(); // 明天
		yesterday.set(Calendar.YEAR, current.get(Calendar.YEAR));
		yesterday.set(Calendar.MONTH, current.get(Calendar.MONTH));
		yesterday.set(Calendar.DAY_OF_MONTH,
				current.get(Calendar.DAY_OF_MONTH) + 1);
		yesterday.set(Calendar.HOUR_OF_DAY, 0);
		yesterday.set(Calendar.MINUTE, 0);
		yesterday.set(Calendar.SECOND, 0);

		Calendar acquired = Calendar.getInstance(); // 后天
		acquired.set(Calendar.YEAR, current.get(Calendar.YEAR));
		acquired.set(Calendar.MONTH, current.get(Calendar.MONTH));
		acquired.set(Calendar.DAY_OF_MONTH,
				current.get(Calendar.DAY_OF_MONTH) + 2);
		acquired.set(Calendar.HOUR_OF_DAY, 0);
		acquired.set(Calendar.MINUTE, 0);
		acquired.set(Calendar.SECOND, 0);
		current.setTime(date);
		String sTime = time.split(" ")[1];
		if (current.before(yesterday) && current.after(today)) {
			if (format.format(yesterday.getTime()).equals(time)) {
				return "明日 " + sTime.substring(0, 5);
			}
			return "今天 " + sTime.substring(0, 5);
		} else if (current.before(acquired) && current.after(yesterday)) {
			if (format.format(acquired.getTime()).equals(time)) {
				return startTime.substring(2, 4) + "月"
						+ startTime.substring(4, 6) + "号"
						+ sTime.substring(0, 5);
			}
			return "明日 " + sTime.substring(0, 5);
		} else {
			return startTime.substring(2, 4) + "月" + startTime.substring(4, 6)
					+ "号" + sTime.substring(0, 5);
		}
	}

	public static boolean compareDate(String DATE1, String DATE2) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH");
		try {
			Date dt1 = df.parse(DATE1);
			Date dt2 = df.parse(DATE2);
			if (dt1.getTime() > dt2.getTime()) {
				return true;
			} else if (dt1.getTime() < dt2.getTime()) {
				return false;
			} else {
				return false;
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return false;
	}

	/**
	 * @Title:hexString2Bytes
	 * @Description:16进制字符串转字节数组
	 * @param src
	 *            16进制字符串
	 * @return 字节数组
	 * @throws
	 */
	public static byte[] hexString2Bytes(String src) {
		int l = src.length() / 2;
		byte[] ret = new byte[l];
		for (int i = 0; i < l; i++) {
			ret[i] = (byte) Integer
					.valueOf(src.substring(i * 2, i * 2 + 2), 16).byteValue();
		}
		return ret;
	}

	/**
	 * 浮点转换为字节
	 * 
	 * @param f
	 * @return
	 */
	public static byte[] float2byte(float f) {

		// 把float转换为byte[]
		int fbit = Float.floatToIntBits(f);

		byte[] b = new byte[4];
		for (int i = 0; i < 4; i++) {
			b[i] = (byte) (fbit >> (24 - i * 8));
		}

		// 翻转数组
		int len = b.length;
		// 建立一个与源数组元素类型相同的数组
		byte[] dest = new byte[len];
		// 为了防止修改源数组，将源数组拷贝一份副本
		System.arraycopy(b, 0, dest, 0, len);
		byte temp;
		// 将顺位第i个与倒数第i个交换
		for (int i = 0; i < len / 2; ++i) {
			temp = dest[i];
			dest[i] = dest[len - i - 1];
			dest[len - i - 1] = temp;
		}

		return dest;

	}

	/**
	 * 字节转换为浮点
	 * 
	 * @param b
	 *            字节（至少4个字节）
	 * @param index
	 *            开始位置
	 * @return
	 */
	public static float byte2float(byte[] b, int index) {
		int l;
		l = b[index + 0];
		l &= 0xff;
		l |= ((long) b[index + 1] << 8);
		l &= 0xffff;
		l |= ((long) b[index + 2] << 16);
		l &= 0xffffff;
		l |= ((long) b[index + 3] << 24);
		return Float.intBitsToFloat(l);
	}

	public static String getStrSize(long fileS) {
		String size = "";
		if (fileS < 1024) {
			size = String.format("%.1f", (double) fileS) + "BT";
			Log.e("size", size + "");
		} else if (fileS < 1048576) {
			size = String.format("%.1f", (double) fileS / 1024) + "KB";
		} else if (fileS < 1073741824) {
			size = String.format("%.1f", (double) fileS / 1048576) + "MB";
		} else {
			size = String.format("%.1f", (double) fileS / 1073741824) + "GB";
		}
		return size;
	}

//	public static String getTotal(ArrayList<CartInfo> cartInfos, CarNum carNum,
//			View v) {
//		String total = "￥ 0";
//		if (cartInfos.size() > 0) {
//			int i = 0;
//			carNum.isGone = false;
//			carNum.num = cartInfos.size();
//			for (CartInfo c : cartInfos) {
//				if (c.getAmount() == 1) {
//					i = i + c.getCount();
//				} else {
//					i = i + c.getCount() * 10;
//				}
//			}
//			total = "￥" + i;
//		} else {
//			carNum.isGone = true;
//			v.setVisibility(View.GONE);
//		}
//		carNum.isResume = false;
//		EventBus.getDefault().post(carNum);
//		return total;
//	}

}
